package com.mega.ebcs.integration.processor;

import java.io.File;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import com.mega.ebcs.util.CamelUtils;

public class FileToClientProcessor implements Processor{
	Logger logger = Logger.getLogger(FileToClientProcessor.class);
	@Override
	public void process(Exchange exchange) throws Exception {
		Message in = exchange.getIn();
		
		 File outboxDirectory = new File("Outbox/"+in.getHeader("fileName"));
		 
		 while (!outboxDirectory.exists() || !CamelUtils.isFileUnlocked(outboxDirectory)) {} //need to modify waiting or monitoring file to minimize the resource

		 String data = FileUtils.readFileToString(outboxDirectory);
		 
		 while (!CamelUtils.isFileUnlocked(outboxDirectory)) {} //need to modify waiting or monitoring file to minimize the resource

		 exchange.getOut().setBody(data.trim());
		 if (CamelUtils.isFileUnlocked(outboxDirectory))
			 FileUtils.forceDelete(outboxDirectory);
		 else {
			 logger.info("failed to delete file, file in use");
		 }
	}

}
